/*
 * @Author: hongbin
 * @Date: 2022-11-19 16:02:36
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-20 22:30:40
 * @Description:
 */
import NextCors from "nextjs-cors";
import { NextApiRequest, NextApiResponse } from "next/types";

/**
 * 只接收指定类型请求并判断数据是否合法
 */
export const receiveRequest = (req: NextApiRequest, res: NextApiResponse<any>, type: "GET" | "POST") => {
    // 接收指定类型请求
    if (req.method != type) {
        res.status(400).json({ data: `未设置${req.method}请求方式` });
        return false;
    }
    // post 请求上传数据不是对象时
    if (type == "POST" && req.body.toString() !== "[object Object]") {
        res.json("错误body");
        return false;
    }
    return true;
};

/**
 * 添加CORS允许
 */
export const AllowCORS = async (req: NextApiRequest, res: NextApiResponse) => {
    await NextCors(req, res, {
        // Options
        methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
        origin: "*",
        optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
    });
};
